package com.lm.paymentcanal.canal;

import com.alibaba.otter.canal.client.CanalConnector;
import com.alibaba.otter.canal.client.CanalConnectors;
import com.alibaba.otter.canal.protocol.CanalEntry.*;
import com.alibaba.otter.canal.protocol.Message;
import com.google.protobuf.InvalidProtocolBufferException;
import com.lm.paymentcanal.user.UserAnalysis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.List;

@Component
@Slf4j
public class CanalClient {

    @Resource
    private UserAnalysis userAnalysis;

    public void run(){
        CanalConnector connector = CanalConnectors.newSingleConnector(new InetSocketAddress("139.198.187.151",
                11111), "example", "canal", "canal");
        int batchSize = 1000;
        try {
            connector.connect();
            connector.subscribe(".*\\..*");
            connector.rollback();
            try {
                while (true) {
                    //尝试从master那边拉去数据batchSize条记录，有多少取多少
                    Message message = connector.getWithoutAck(batchSize);
                    long batchId = message.getId();
                    int size = message.getEntries().size();
                    if (batchId == -1 || size == 0) {
                        Thread.sleep(1000);
                    } else {
                        dataHandle(message.getEntries());
                    }
                    connector.ack(batchId);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (InvalidProtocolBufferException e) {
                e.printStackTrace();
            }
        } finally {
            connector.disconnect();
        }
    }
    /**
     * 数据处理
     *
     * @param entrys
     */
    private void dataHandle(List<Entry> entrys) throws InvalidProtocolBufferException {
        for (Entry entry : entrys) {
            if(entry.getHeader().getSchemaName().equals("hc")){
                return;
            }
            if (EntryType.ROWDATA == entry.getEntryType()) {
                RowChange rowChange = RowChange.parseFrom(entry.getStoreValue());
                EventType eventType = rowChange.getEventType();
                //打印Header信息
                log.info(String.format("================》; binlog[FILE:%s-OFFSET:%s] , name[DATABASE:%s,TABLE:%s] , eventType : %s",
                        entry.getHeader().getLogfileName(), entry.getHeader().getLogfileOffset(),
                        entry.getHeader().getSchemaName(), entry.getHeader().getTableName(),
                        eventType));

                if("t_account".equals(entry.getHeader().getTableName())){
                    userAnalysis.analyseUser(rowChange);
                }

                //判断是否是DDL语句
                if (rowChange.getIsDdl()) {
                   log.info("================》;isDdl: true,sql:" + rowChange.getSql());
                }
                //获取RowChange对象里的每一行数据，打印出来
                for (RowData rowData : rowChange.getRowDatasList()) {
                    //如果是删除语句
                    if (eventType == EventType.DELETE) {
                        printColumn(rowData.getBeforeColumnsList());
                        //如果是新增语句
                    } else if (eventType == EventType.INSERT) {
                        printColumn(rowData.getAfterColumnsList());
                        //如果是更新的语句
                    } else if (eventType == EventType.UPDATE){
                        //变更前的数据
                        log.info("------->; before");
                        printColumn(rowData.getBeforeColumnsList());
                        //变更后的数据
                        log.info("------->; after");
                        printColumn(rowData.getAfterColumnsList());
                    }
                }

            }
        }
    }

    private void printColumn(List<Column> columns) {
        for (Column column : columns) {
            System.out.println(column.getName() + " : " + column.getValue() + "    update=" + column.getUpdated());
        }
    }
}
